#!/bin/sh
. /etc/utils.sh

runoregano="/app/oregano/runoregano"

if ! is-html-tv-ui; then
  echo "configured for sage"
  exit 0
fi

parent_comm=$(ps -o comm= $PPID)
echo $PPID
if [ "$parent_comm" = "gsetsid" ]; then
  # Special case; when something executes '<action> oregano' it goes
  # via <action> and then gsetsid - but we want the real parent. So
  # let's head up the chain to the real parent.
  action_pid=$(cat /proc/$PPID/status | grep PPid | cut -d':' -f2 | sed -r 's/\s+//g')
  if [ "$action_pid" != "" ]; then
    real_ppid=$(cat /proc/"$action_pid"/status | grep PPid | cut -d':' -f2 | sed -r 's/\s+//g')
    real_parent=$(ps -o comm= $real_ppid)
    parent_comm="$parent_comm ($real_parent)"
  fi
fi

case "$1" in
  start)
    echo "S99oregano: start called by $parent_comm" | logos oregano
    (
      wait-until-created /tmp/mcnmp_ready
      wait-until-created /tmp/time.synced
      if is-tv-box; then
        (
          if [ "$(id -u)" != "0" ]; then
            # We are already not running as root, keep current user
            $runoregano
            touch /tmp/renice_oregano
          else
            nice -n -5 setuid appclient:video $runoregano
          fi
        ) 2>&1 | logos oregano 0 20000000 &
      fi
    ) &
    ;;
  stop)
    echo "S99oregano: stop called by $parent_comm" | logos oregano
    # If startupvideo is running, it prevents miniclient from starting up.
    pkillwait -x startupvideo &
    # Stop the scripts invoked above due to 'start oregano' (which will also
    # stop any babysitters they may have).
    ( pkillwait -x 'runoregano' ;
      # End the Oregano start_chromium binary (which will also end its babysitter).
      pkillwait -x 'start_chromium' ;
      pkillwait -x 'browser_shell' ) &
    # End any dangling HTTP request Futures from authTokens.dart attempts.
    pkillwait -f '(dart.*)([a]uthTokens\.dart)' &
    pkillwait -x waitpower &
    pkillwait -x netflix &
    pkillwait -x vudu &
    wait
    ;;
  restart)
    echo "S99oregano: restart called by $parent_comm" | logos oregano
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
